package org.rslai.tcedit.domain;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import org.hibernate.validator.*;

/**
 * 用户信息
 * 
 * @author rslai
 */
@Entity
@Table(name = "t_user")
public class User extends UUIDSupport {

	private String username; // 用户名
	private String password; // 密码
	private String realName; // 真实姓名
	private String email; // 邮件地址
	private Date createdDate; // 创建日期
	private Boolean locked = false; // 是否被锁定
	private UserDetails userDetails; // 用户详细信息
	private Set<Role> roles = new HashSet<Role>(0); // 角色列表

	public User() {
	}

	@Column(nullable = false, length = 40)
	@Pattern(regex = "[a-z0-9@.]{6,40}", message = "用户名只能由英文字母和数字构成，长度为6-40个字符")
	public String getUsername() { return username; }
	public void setUsername(String username) { this.username = username; }

	@Column(nullable = false, length = 32)
	@Length(max = 32, message = "密码请限制在32个字以内")
	public String getPassword() { return password; }
	public void setPassword(String password) { this.password = password; }

	@Column(nullable = false, length = 20)
	@Length(max = 20, message = "真实姓名请限制在20字以内")
	public String getRealName() { return realName; }
	public void setRealName(String realName) { this.realName = realName; }

	@Column(nullable = false, length = 50)
	@Email(message = "Email地址格式错误（示例：xyz@abc.com）")
	public String getEmail() { return email; }
	public void setEmail(String email) { this.email = email; }

	@Column(nullable = false, updatable = false)
	public Date getCreatedDate() { return createdDate; }
	public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; }

	@Transient
	public String getCreatedDateAsString() {
		return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(createdDate);
	}

	@Column(nullable = false)
	public Boolean getLocked() { return locked; }
	public void setLocked(Boolean locked) { this.locked = locked; }

	@OneToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.ALL)
	@JoinColumn(unique = true)
	public UserDetails getUserDetails() { return userDetails; }
	public void setUserDetails(UserDetails userDetails) { this.userDetails = userDetails; }

    @ManyToMany(fetch = FetchType.EAGER, targetEntity=Role.class)
    public Set<Role> getRoles() { return roles; }
    public void setRoles(Set<Role> roles) { this.roles = roles; }

    /**
     * Display name will return name if name is not empty, otherwise username.
     */
    @Transient
    public String getDisplayName() {
        if(realName==null || "".equals(realName.trim()))
            return username;
        return realName;
    }

}
